package com.it.share;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@ComponentScan(basePackages = "com.it.share")
@Configuration
public class AppConfig {

    static String table_sql="DROP TABLE IF EXISTS user;\n" +
            "CREATE TABLE user\n" +
            "(\n" +
            "\tid BIGINT(20) NOT NULL COMMENT '主键ID',\n" +
            "\tname VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',\n" +
            "\tPRIMARY KEY (id)\n" +
            ");";

    @Bean
    public DataSource b0() {
        DataSource d1 = new SingleConnectionDataSource(
                "jdbc:h2:mem:test1",
                "root",
                "root",
                true
        );
        DataSource d2 = new SingleConnectionDataSource(
                "jdbc:h2:mem:test2",
                "root",
                "root",
                true
        );

        List<DataSource> ds=new ArrayList<>();

        ds.add(d1);
        ds.add(d2);

        //初始化表结构
        for (DataSource dataSource : ds) {
            try {
                Connection connection = dataSource.getConnection();
                PreparedStatement preparedStatement = connection.prepareStatement(table_sql);
                preparedStatement.execute();
            } catch (SQLException e) {
            }
        }

        return new MgDataSource(ds);
    }

    @Bean
    public JdbcTemplate b1(DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.setDatabaseProductName("h2");
        return jdbcTemplate;
    }

}
